package org.geektimes.configuration.microprofile.config.source.servlet;

import javax.servlet.*;
import javax.servlet.annotation.HandlesTypes;
import java.util.EventListener;
import java.util.Set;

@HandlesTypes(value = {EventListener.class,Servlet.class,Filter.class})
public class ServletConfigInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> containerClasses, ServletContext servletContext) throws ServletException {
        // 增加 ServletContextListener
        servletContext.addListener(ServletContextConfigInitializer.class);


        if (containerClasses != null) {
            for (Class<?> containerClass : containerClasses) {
                if (containerClass.isAssignableFrom(EventListener.class)) {
                    // 增加 ServletContextListener ServletContextConfigInitializer.class
                    servletContext.addListener((Class<? extends EventListener>) containerClass);
                } else if (containerClass.isAssignableFrom(Filter.class)) {
                    // 增加 Filter
                    servletContext.addFilter(containerClass.getSimpleName(), (Class<? extends Filter>) containerClass);
                } else if (containerClass.isAssignableFrom(Servlet.class)) {
                    // 增加 HttpServlet
                    servletContext.addServlet(containerClass.getSimpleName(), (Class<? extends Servlet>) containerClass);
                }
            }
        } else {
            servletContext.log("");
        }
    }
}
